package priv.pfz.raft.peer;

import java.util.Timer;
import java.util.TimerTask;

/**
 * timerTask的执行和对timer的操作是排队无并发的
 * @author pengfangzhou
 * @date 2022/2/4 13:35
 */
public class AtomicTimer {
    private Timer timer = new Timer();
    private final Object lock = new Object();
    private volatile int version = 0;

    public void schedule(Runnable runnable, long delay) {
        synchronized (lock) {
            timer.schedule(new TimerTask() {
                private int taskVersion = version;

                @Override
                public void run() {
                    if (taskVersion != version) {
                        return;
                    }
                    synchronized (lock) {
                        if (taskVersion != version) {
                            return;
                        }
                        runnable.run();
                    }
                }
            }, delay);
        }
    }

    public void cancel() {
        synchronized (lock) {
            timer.cancel();
            version++;
            timer = new Timer();
        }
    }

    @Override
    public String toString() {
        return "AtomicTimer";
    }
}
